package com.k8.rpc.url;


import com.k8.common.util.StrUtil;

import static com.k8.common.constants.CommonConstants.MID_INTERVAL;

//用于指定唯一的接口实现类的签名
public class ApiSignature {//签名
    private final String regex = "^/([a-zA-Z_][a-zA-Z0-9_]*)(\\.[a-zA-Z_][a-zA-Z0-9_]*)*_(.*)_.*$";
    private final String protocol;
    //由接口名:group:version构成
    private final String path;
    private final String interfaceName;
    private final String group;
    private final String version;
    private final String registerPath;

    public String getInterfaceName() {
        return interfaceName;
    }

    public String getGroup() {
        return group;
    }

    public String getVersion() {
        return version;
    }

    public ApiSignature(String protocol, String path, String registerPath) {
        if (StrUtil.isEmpty(protocol)) throw new IllegalArgumentException("This protocol is empty");
        this.protocol = protocol;
        if (StrUtil.isEmpty(path)) throw new IllegalArgumentException("This path is empty");
        if (!path.startsWith("/")) path = "/" + path;
        if (!path.matches(regex)) throw new IllegalArgumentException("This path is error, path:" + path);
        this.path = path;
        String[] split = path.split("/")[1].split("_");
        this.interfaceName = split[0];
        this.group = split[1];
        this.version = split[2];
        this.registerPath = registerPath;
    }

    public ApiSignature(URL url, String registerPath) {
        this.protocol = url.getProtocol();
        if (StrUtil.isEmpty(this.protocol)) throw new IllegalArgumentException("This protocol is empty");
        this.path = url.getPath();
        if (!this.path.matches(regex)) throw new IllegalArgumentException("This path is error, path:" + path);
        this.interfaceName = url.getInterface();
        this.group = url.getGroup();
        this.version = url.getVersion();
        this.registerPath = registerPath;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getPath() {
        return path;
    }

    public String getSignature() {
        return (protocol + MID_INTERVAL + path).replaceAll("/", "");
    }

    public String getRegisterPath() {
        return registerPath;
    }
}
